package com.teambsc4.todo.views

import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.teambsc4.todo.entities.TaskStatus
import com.teambsc4.todo.entities.taskPriority
import com.teambsc4.todo.viewmodel.MainPageViewModel
import com.teambsc4.todo.viewmodel.StoreData
import kotlinx.coroutines.launch

@Composable
fun TodoListBox(viewModel: MainPageViewModel) {

    val dataStore = remember {
        StoreData()
    }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument()
    ) {
        it?.let { uri ->
            context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
            scope.launch {
                dataStore.storeImage(context, uri.toString())
            }
        }
    }

    var showDialog by remember {
        mutableStateOf(false)
    }

    Column(
        modifier = Modifier
            .padding(16.dp)
            .verticalScroll(rememberScrollState())
    ) {
        viewModel.tasks.forEach { item ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp)
                    .shadow(elevation = 4.dp),
                shape = RoundedCornerShape(8.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "Title: ${item.title}"
                    )
                    Text(
                        text = "Description: ${item.description}"
                    )
                    Text(
                        text = "priority: ${item.priority.drop(2)}"
                    )
                    Text(
                        text = "BeginTime: ${item.beginTime}"
                    )
                    Text(
                        text = "EndTime: ${viewModel.getEndTime(item.endTime)}"
                    )
//                    Text(
//                        text = "Localization: ${item.gps}"
//                    )
                    Text(
                        text = "Status: ${item.status}"
                    )
                    Spacer(
                        modifier = Modifier.height(4.dp)
                    )
                    Row {
                        Button(onClick = {
                            showDialog = true
                            viewModel.currentItem(item.id)
                        }) { Text("Edit") }
                        Spacer(
                            modifier = Modifier.width(10.dp)
                        )
                        Button(onClick = {
                            viewModel.onDeleteTaskButton(item)
                        }) {
                            Text("Delete")
                        }
                    }
                }
            }
        }
        if (showDialog) {
            AlertDialog(
                onDismissRequest = {
                    showDialog = false
                },
                title = {
                    Text(text = "Update a Task")
                },
                text = {
                    Column {
                        TextField(
                            value = viewModel.taskTitle,
                            onValueChange = { viewModel.updateTitle(it) },
                            label = { Text("Title") }
                        )

                        TextField(
                            value = viewModel.taskDescription,
                            onValueChange = { viewModel.updateDescription(it) },
                            label = {
                                Text("Description")
                            }
                        )

                        TextField(
                            value = viewModel.taskEndTime,
                            onValueChange = { viewModel.updateEndTime(it) },
                            label = { Text("EndTime（day）") },
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Number
                            )
                        )
                        Row {
                            Column(modifier = Modifier.padding(5.dp)) {
                                DropdownMenu(
                                    expanded = viewModel.isDropdownExpanded,
                                    onDismissRequest = {
                                        viewModel.isDropdownExpanded = false
                                    }
                                ) {
                                    TaskStatus.forEach {
                                        DropdownMenuItem(
                                            text = { Text(text = it) },
                                            onClick = { viewModel.updateStatus(it) })
                                    }
                                }
                                Text(text = "Selected Status:\n ${viewModel.taskState}")
                                IconButton(onClick = { viewModel.isDropdownExpanded = true }) {
                                    Icon(
                                        imageVector = Icons.Default.ArrowDropDown,
                                        contentDescription = "Open Dropdown"
                                    )
                                }
                            }
                            Column(modifier = Modifier.padding(5.dp)) {
                                //优先级
                                DropdownMenu(
                                    expanded = viewModel.isDropdownExpanded2,
                                    onDismissRequest = {
                                        viewModel.isDropdownExpanded2 = false
                                    }
                                ) {
                                    taskPriority.forEach {
                                        DropdownMenuItem(
                                            text = { Text(text = it.drop(2)) },
                                            onClick = { viewModel.updatePriority(it) })
                                    }
                                }
                                Text(text = "Selected Priority:\n ${viewModel.taskPriority.drop(2)}")
                                IconButton(onClick = { viewModel.isDropdownExpanded2 = true }) {
                                    Icon(
                                        imageVector = Icons.Default.ArrowDropDown,
                                        contentDescription = "Open Dropdown"
                                    )
                                }
                            }
                        }
                        Column {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(100.dp), contentAlignment = Alignment.Center
                            ) {

                                if (viewModel.imageUri.toString().isNotBlank()) {
                                    AsyncImage(
                                        model = viewModel.imageUri,
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(280.dp),
                                        contentScale = ContentScale.Crop
                                    )
                                } else {
                                    Text(
                                        text = "no pictures",
                                        modifier = Modifier
                                            .padding(40.dp),
                                    )
                                }

                            }
                            IconButton(onClick = {
                                launcher.launch(arrayOf("image/"))
                            }) {
                                Icon(imageVector = Icons.Default.Add, contentDescription = "Add Photo")
                            }
                        }
                    }
                },
                //Update
                confirmButton = {
                    Button(enabled = viewModel.isConfirmEnabled(), onClick = {
                        viewModel.upDateTask()
                        showDialog = false
                        viewModel.clearInputFields()
                    }) {
                        Text("Update")
                    }
                },
                //Cancel
                dismissButton = {
                    Button(onClick = {
                        showDialog = false
                        viewModel.clearInputFields()
                    }) {
                        Text("Cancel")
                    }
                }
            )
        }
    }
}






